package com.vegan_friendly;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class RestListActivity extends Activity {

	private SimpleCursorAdapter dataAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rest_list);
		
		
		Cursor c = DBAdapter.Inst().getAllRestForList();
		int  i = c.getCount();
		
		String[] columns = new String[] {
			    DBAdapter.R_MainPicture,
			    DBAdapter.R_Name,
			    DBAdapter.R_Address,
			    DBAdapter.R_Phone
			  };
		
		int[] to = new int[] { 
			    R.id.picture,
			    R.id.name,
			    R.id.address,
			    R.id.phone
			  };
		
		//dataAdapter = new SimpleCursorAdapter(
		dataAdapter = new MySimpleAdapter(
			    this, R.layout.rest_row, 
			    c, 
			    columns, 
			    to
			    );
			 
		ListView listView = (ListView) findViewById(R.id.listViewRest);
		listView.setAdapter(dataAdapter);
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(RestListActivity.this, RestViewActivity.class);
				RestListActivity.this.startActivity(intent);
				
			}
			
		});
	
		/*LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		Cursor c = DBAdapter.Inst().getAllRest();
		c.moveToFirst();
		int num = c.getCount();
		
		String name = c.getString(DBAdapter.ColIndex.Name);
		String picUrl = c.getString(DBAdapter.ColIndex.PicturesUrl);
		//locationManager.getBestProvider(0x00000002,)
		
		ListView lvRest = (ListView)findViewById(R.id.listViewRest);
		
		ArrayList<String> arRest = new ArrayList<String>();
		arRest.add(name);
		arRest.add(picUrl);
		MyAdapter adapter = new MyAdapter(this, c);

		lvRest.setAdapter(adapter);

		lvRest.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				
			}
        });
		*/
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

		StrictMode.setThreadPolicy(policy); 
		
	}
	
	class MySimpleAdapter extends SimpleCursorAdapter {

		private Cursor dbRest = null;
		private Context context;
		private Activity activity;

		
		@SuppressWarnings("deprecation")
		public MySimpleAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
			this.dbRest = c;
			this.context = context;
		}
	    @Override
	    public View getView(int position, View convertView, ViewGroup parent){
	        //String myText = getItem(position);   
	    	
	    	
	    	if(dbRest ==null){
	    		Log.w("MyAdapter:getView", "dbRest is null");
	    		return null;
	    	}
	 

	        if(convertView == null){ // If the View is not cached
	            // Inflates the Common View from XML file
	            convertView = View.inflate(context, R.layout.rest_row, null);
	        }

	        dbRest.moveToPosition(position);
	        
	        TextView tvName = (TextView)convertView.findViewById(R.id.name);
	        tvName.setText(dbRest.getString(2));
	        
	        TextView tvAddress = (TextView)convertView.findViewById(R.id.address);
	        tvAddress.setText(dbRest.getString(3));
	        
	        TextView tvPhone = (TextView)convertView.findViewById(R.id.phone);
	        tvPhone.setText(dbRest.getString(4));
	        
	       /* TextView tvPic = (TextView)convertView.findViewById(R.id.picture);
	        String url = dbRest.getString(1);
	        
	        try {

					URL aURL = new URL(url);
					URLConnection conn = aURL.openConnection();
					conn.connect();
					InputStream is = conn.getInputStream();

					BufferedInputStream bis = new BufferedInputStream(is);
				
					Bitmap bm = BitmapFactory.decodeStream(bis);
					bis.close();
					is.close();
					
					Drawable d =new BitmapDrawable(bm);
					tvPic.setBackgroundDrawable(d);
					tvPic.setText("");
					//d.setId("1");
					//tvPic.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);// wherever u want the image relative to textview
	            } catch (IOException e) {
	            	Log.e("DEBUGTAG", "Remote Image Exception", e);
	            } 
*/
	        // Of course you will need to set the same ID in your item list XML layout.

	        return convertView;
	    }
	}
	class MyAdapter extends BaseAdapter{
	    private LayoutInflater inflater;
	    private Cursor dbRest = null;

	    public MyAdapter(Context context, Cursor dbRest){
	    // Caches the LayoutInflater for quicker use
	    this.inflater = LayoutInflater.from(context);
	    // Sets the events data
	    this.dbRest = dbRest;
	    }

	    public int getCount() {
	        return this.dbRest.getCount();
	    }
	    
	    @Override
	    public View getView(int position, View convertView, ViewGroup parent){
	        //String myText = getItem(position);   
	    	dbRest.moveToPosition(position);
	    	
	    	if(dbRest ==null){
	    		Log.w("MyAdapter:getView", "dbRest is null");
	    		return null;
	    	}
	 

	        if(convertView == null){ // If the View is not cached
	            // Inflates the Common View from XML file
	            convertView = this.inflater.inflate(R.layout.rest_row, null);
	        }

	        
	        
	        TextView tvName = (TextView)convertView.findViewById(R.id.name);
	        tvName.setText(dbRest.getString(DBAdapter.ColIndex.Name));
	        
	        TextView tvAddress = (TextView)convertView.findViewById(R.id.address);
	        tvAddress.setText(dbRest.getString(DBAdapter.ColIndex.Address));
	        
	        TextView tvPic = (TextView)convertView.findViewById(R.id.picture);
	        String url = dbRest.getString(DBAdapter.ColIndex.MainPicture);
	        
	        try {
					/* Open a new URL and get the InputStream to load data from it. */
					URL aURL = new URL(url);
					URLConnection conn = aURL.openConnection();
					conn.connect();
					InputStream is = conn.getInputStream();
					/* Buffered is always good for a performance plus. */
					BufferedInputStream bis = new BufferedInputStream(is);
					/* Decode url-data to a bitmap. */
					Bitmap bm = BitmapFactory.decodeStream(bis);
					bis.close();
					is.close();
					
					Drawable d =new BitmapDrawable(bm);
					tvPic.setBackgroundDrawable(d);
					tvPic.setText("");
					//d.setId("1");
					//tvPic.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);// wherever u want the image relative to textview
	            } catch (IOException e) {
	            	Log.e("DEBUGTAG", "Remote Image Exception", e);
	            } 

	        // Of course you will need to set the same ID in your item list XML layout.

	        return convertView;
	    }

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

	}

}
